package com.zp.datax.core;


import com.zp.datax.core.model.DataxJobTrigger;
import com.zp.datax.core.util.TimeUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * 结束时间条件处理器
 *
 * @author bruce
 * @date 2019-07-15
 */
@Slf4j
public class EndTimeCondition extends Condition {

    protected EndTimeCondition(Condition condition) {
        super(condition);
    }

    @Override
    public Object[] append(String str) throws IllegalArgumentException {

        Object[] objarray = getObjarray(str);
        String condition = Objects.toString(objarray[0]);
        Long currentTimeMillis = Long.valueOf(Objects.toString(objarray[1]));
        Long endTime;

        DataxJobTrigger dataxJobTrigger = getDataxJobTrigger();
        Integer range = dataxJobTrigger.getRange();
        Integer unit = dataxJobTrigger.getUnit();
        Long startTime = dataxJobTrigger.getBizStarTime();

        if (startTime.compareTo(Long.valueOf(currentTimeMillis)) == -1
                && range.compareTo(0) == 1
                && unit.compareTo(0) == 1
                && unit.compareTo(7) == -1
                && str.contains("startTime")) {//有设置同步范围和单位并且起始时间不为空优先配对
            endTime = ConditionUnit.plus(startTime, Long.valueOf(range), unit);
        } else {
            if (!str.contains("endTime")) {
                return objarray;
            }

            if (startTime.compareTo(0L) == 0
                    && !str.contains("startId")) {
                String message = String.format(
                        "同步失败 :: taskId :: %s, 根据分析本次同步的参数startTime起始时间值不能为0，可能原因分析：\n1、参数名与同步范围组合错误；\n2、未指定参数名startTime起始时间；\n建议手动指定参数值进行同步；"
                        , dataxJobTrigger.getTaskId());
                log.error(message);
                log.info("dataxJobTrigger :: {}", dataxJobTrigger);
                throw new IllegalArgumentException(message);
            }

            endTime = currentTimeMillis;

        }

        objarray[0] = String.format("%sendTime=%s,", condition, TimeUtil.parserT(endTime));
        dataxJobTrigger.setBizEndTime(endTime);

        return objarray;
    }
}
